package com.cjx.print.helper;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.cjx.print.App;
import com.cjx.print.interfaces.Callback;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * create by cjx on 2025/4/21
 * desc:
 */
public class LeBluetoothHelper {

    private BluetoothLeScanner bluetoothLeScanner;
    private Callback<BluetoothDevice> deviceHandlerCallback;
    private boolean scanAfterOpen = false;

    private final BroadcastReceiver blueToothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
            switch (blueState) {
                case BluetoothAdapter.STATE_ON:
                    if (scanAfterOpen) {
                        log("蓝牙已打开---");
                        startScan();
                    }
                    break;
            }
        }
    };

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            //蓝牙发现
            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                log("蓝牙开始搜索");
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                log("蓝牙搜索结束");
                deviceHandlerCallback.callback(null);
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
                log("蓝牙配对状态改变: " + state + ": " + device.getName());
                if (deviceHandlerCallback != null) {
                    deviceHandlerCallback.callback(device);
                }
            } else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
                log("蓝牙请求配对: " + device.getName());
            }
        }
    };

    // 低功耗蓝牙扫描
    private final ScanCallback leScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BluetoothDevice device = result.getDevice();
            if (deviceHandlerCallback != null) {
                deviceHandlerCallback.callback(device);
            }
        }
    };


    private static final class HelperHolder {
        static final LeBluetoothHelper helper = new LeBluetoothHelper();
    }

    public static LeBluetoothHelper getInstance() {
        return HelperHolder.helper;
    }

    private LeBluetoothHelper() {
        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
//        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
//        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
//        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        App.app.registerReceiver(receiver, intentFilter);

        App.app.registerReceiver(blueToothReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    }

    // 打开蓝牙
    public boolean openBluetooth() {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            return bluetoothAdapter.isEnabled() || bluetoothAdapter.enable();
        } catch (Exception e) {
            return false;
        }
    }


    public void closeBluetooth() {
        BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
        if (defaultAdapter.isEnabled()) {
            defaultAdapter.disable();
        }
    }

    public void setDeviceHandlerCallback(Callback<BluetoothDevice> callback) {
        this.deviceHandlerCallback = callback;
    }

    public Set<BluetoothDevice> getBoundDevices() {
        return BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    }

    public void startScan() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter.isEnabled()) {
            scanAfterOpen = false;
            stopScan();
            log("开始扫描");
            ScanSettings settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();

            List<ScanFilter> filters = new ArrayList<>();
            // 可以添加过滤条件，如只扫描特定服务UUID的设备
            // filters.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString("0000xxxx-0000-1000-8000-00805f9b34fb")));
            // 低功耗选这个
            bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
            bluetoothLeScanner.startScan(filters, settings, leScanCallback);

        } else {
            log("延迟开始扫描");
            scanAfterOpen = true;
        }
    }

    public void stopScan() {
        log("停止扫描");
        // 低功耗选这个
        if (bluetoothLeScanner != null) {
            bluetoothLeScanner.stopScan(leScanCallback);
            bluetoothLeScanner = null;
        }
    }

    public void bondDevice(String address, String pin, Callback<Boolean> bindCallback) {
        BluetoothDevice bluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
        // 获取 BluetoothDevice 类的类对象
        Class<?> btClass = BluetoothDevice.class;
        // 获取 createBond 方法的引用
        try {
            Method setPinMethod = BluetoothDevice.class.getMethod("setPin", byte[].class);
            setPinMethod.invoke(bluetoothDevice, pin.getBytes());

            Method createBondMethod = btClass.getMethod("createBond");
            Object result = createBondMethod.invoke(bluetoothDevice);
            log("配对结果：" + result);
            if (result != null) {
                bindCallback.callback((Boolean) result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void log(String message) {
        System.out.println("Bluetooth >>> " + message);
    }
}
